package controller

import (
	"ci-control-backend/common"
	"ci-control-backend/common/db"
	"ci-control-backend/common/file"
	"ci-control-backend/common/httpx"
	"ci-control-backend/model"
	"ci-control-backend/tools"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/pkg/errors"
	"time"
)

type RecordController struct{}

func (*RecordController) DelRecord(ctx *httpx.Context) any {
	id := ctx.ParamUint("id")
	record, err := model.GetRecordByID(id)
	if err != nil {
		return errors.WithStack(err)
	}
	if record == nil {
		return errors.Errorf("不存在id=%v的构建记录", id)
	}
	if _, err := record.Delete(); err != nil {
		return errors.WithStack(err)
	}
	return "已删除构建记录"
}

func (*RecordController) GetRecordList(ctx *httpx.Context) any {
	var page, pageSize, planId int
	err := ctx.MultiQuery(gin.H{
		"page":     &page,
		"pageSize": &pageSize,
		"planId":   &planId,
	})
	if err != nil {
		return err
	}

	// 分页查询
	pageable := db.QueryPage(&model.Record{})
	// 倒序
	pageable.SQL.Desc("id")
	if planId != 0 { // 如果计划id不为0，则进行筛选
		pageable.SQL.Where("plan_id = ?", planId)
	}
	// 执行查询
	pageResult, err := pageable.PageParam(page, pageSize).Exec()
	if err != nil {
		return err
	}
	for _, record := range pageResult.PageData {
		record.PushKeys = ""
	}
	return pageResult
}

func (*RecordController) GetLog(ctx *httpx.Context) any {
	var id uint
	if err := ctx.Query("id", &id); err != nil {
		return errors.WithStack(err)
	}

	record, err := model.GetRecordByID(id)
	if err != nil {
		return errors.WithStack(err)
	}
	if record == nil {
		return errors.Errorf("不存在id=%v的构建记录", id)
	}

	bt, err := file.Read("record", fmt.Sprintf("%v", record.ID))
	if err != nil {
		return errors.WithStack(err)
	}

	return gin.H{"log": string(bt), "taskStatus": record.ExecResult}
}

func (*RecordController) PushLog(ctx *httpx.Context) any {
	key := ctx.Param("key")

	record, err := model.GetRecordByPushKeys(key)
	if err != nil {
		return errors.WithStack(err)
	}
	if record == nil {
		return errors.Errorf("不存在keys=%v的构建记录", key)
	}

	var req struct {
		LogContext string `json:"log_context"`
		Code       uint   `json:"code"`
	}

	err = ctx.ShouldBindJSON(&req)
	if err != nil {
		return errors.WithStack(err)
	}

	// 将日志文本添加至文件末尾
	if err := file.Append("record", fmt.Sprintf("%v", record.ID), []byte(req.LogContext)); err != nil {
		return errors.WithStack(err)
	}

	// 如果是已完成、任务失败，则更新任务结束时间
	if req.Code == common.FINISH || req.Code == common.FAIL {
		record.EndTime = tools.TimePtr(time.Now())
	}

	record.ExecResult = req.Code
	_, _ = record.Update()

	return "写入成功"
}
